package com.hxzy.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.controller.admin.mapstruct.OrdersConvert;
import com.hxzy.controller.admin.orders.req.OrdersReq;
import com.hxzy.controller.admin.orders.req.UpdateConsigneeReq;
import com.hxzy.controller.admin.orders.resp.OrderViewResp;
import com.hxzy.controller.admin.orders.resp.OrdersResp;
import com.hxzy.controller.admin.orders.resp.OrdersStatisticResp;
import com.hxzy.controller.admin.product.resp.ProductResp;
import com.hxzy.controller.mobile.cart.resp.MobileCartResp;
import com.hxzy.controller.mobile.order.req.OrderCreateReq;
import com.hxzy.entity.AddressBook;
import com.hxzy.entity.OrderDetail;
import com.hxzy.entity.Orders;
import com.hxzy.entity.Product;
import com.hxzy.service.*;
import com.hxzy.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author Administrator
* @description 针对表【orders(订单表)】的数据库操作Service实现
* @createDate 2023-06-28 16:38:44
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 商品信息
     */
    @Autowired
    private ProductService productService;

    /**
     * 购物车
     */
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 收货地址
     */
    @Autowired
    private AddressBookService  addressBookService;

    /**
     * 订单明细
     */
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     *  remark:备注,
     *    payMethod:2,支付宝支付
     *    addressBookId:收货人地址
     * 	 merchantId: 商家ID
     * 1、根据商家ID用户ID查询购物车的内容
     * 2、下订单（orders）插入订单汇总信息
     * 3、判断 库存够不够，如果不够结束操作，如果够了order_detail插入订单明细，并且更新库存（库存！=-1）
     * 4、返回订单(会员积分更新，会员短信通知，会员邮件通知，扩展)
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String createOrder(OrderCreateReq req) {
        //1、根据商家ID用户ID查询购物车的内容
        List<MobileCartResp> cartList=this.shoppingCartService.findByMerchantId(req.getMerchantId());
        if(cartList.isEmpty()){
            throw new ServiceException(AckCode.CART_EMPTY);
        }

        //2、查询收货地址
        AddressBook addressBook = this.addressBookService.getById(req.getAddressBookId());
        if(Objects.isNull(addressBook) || addressBook.getIsDeleted().equals("1")){
            throw new ServiceException(AckCode.ADDRESS_NOT_FOUND);
        }

        //订单表实体
        List<OrderDetail> orderDetailList=new ArrayList<>();
        //3、循环处理购物车

        BigDecimal  totalMomey=new BigDecimal(0);

        for(MobileCartResp cart: cartList){
            //3.1、查询商品，商品还在不在，库存够不够
            ProductResp productDB = this.productService.lockById(cart.getDishId());
            if(Objects.isNull(productDB)){
                throw new ServiceException(AckCode.DATA_NOT_FOUND);
            }
            if(productDB.getIsgrounding().equals("0")){
                throw new ServiceException(AckCode.PRODUCT_DELISTING);
            }
            //要扣库存
            if(productDB.getNum()!=-1){
                //库存不足
               if(cart.getNumber()> productDB.getNum()){
                   throw new ServiceException(AckCode.PRODUCT_STORE_EMPTY);
               }

               //库存足够，扣库存
               int count=this.productService.descNum(productDB.getId(),  cart.getNumber());
               if(count==0){
                   throw new ServiceException(AckCode.DATABASE_ERROR);
               }
            }

            //累加金额=数额 * 单价格
            totalMomey=totalMomey.add(new BigDecimal(cart.getNumber() * productDB.getPrice()));


           //3，4、构造一个订单明细
            OrderDetail  orderDetailEntity=new OrderDetail();
            orderDetailEntity.setDishId(cart.getDishId());
            orderDetailEntity.setNumber(cart.getNumber());
            orderDetailEntity.setAmount(new BigDecimal(productDB.getPrice()));
            orderDetailEntity.setName(cart.getName());
            orderDetailEntity.setImage(cart.getImage());
            orderDetailEntity.setDishFlavor(cart.getDishFlavor());
            orderDetailEntity.setMerchantId(cart.getMerchantId());
            orderDetailList.add(orderDetailEntity);
        }

        //4、向订单表插入订单信息
        Orders  orders=new Orders();
        orders.setMerchantId(req.getMerchantId());
        //实际收货人
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setRemark(req.getRemark());
        orders.setAddressBookId(req.getAddressBookId());
        orders.setUserId(new Long(WaimaiThreadLocal.mobileLoginThreadLocal.get().getId()));
        //支付宝
        orders.setPayMethod(req.getPayMethod()+"");
        //待支付
        orders.setStatus("1");
        orders.setAmount(totalMomey);
        //订单号(雪花算法)
        orders.setNumber(IdUtil.getSnowflakeNextIdStr());
        //下订单那个人
        orders.setUserName(WaimaiThreadLocal.mobileLoginThreadLocal.get().getUserName());
        orders.setOrderTime(new Date());

         this.getBaseMapper().insert(orders);

        //5、向订单明细表中插入信息
        for(OrderDetail  detail: orderDetailList){
            //赋值订单号
            detail.setOrderId(orders.getId());
            this.orderDetailService.save(detail);
        }

        // 删除购物车中当前用户，当前商家的信息
        this.shoppingCartService.cleanCart(req.getMerchantId());

        return orders.getNumber();
    }

    /**
     * 根据订单查询商家名称
     * @param orderNumber
     * @return
     */
    @Override
    public String searchByMerchandiserName(String orderNumber) {
        return this.baseMapper.searchByMerchandiserName(orderNumber);
    }

    /**
     * 分页查询
     * @param req
     * @return
     */
    @Override
    public PageInfo<OrdersResp> search(OrdersReq req) {
        return PageHelper.startPage(req.getPage(),req.getSize())
                .doSelectPageInfo(()->{
                    ordersMapper.search(req);
                });
    }

    /**
     * 订单统计数据
     * @return
     */
    @Override
    public OrdersStatisticResp ordersStatistic() {
        AdminLoginResp current = WaimaiThreadLocal.getCurrent();
        Long merchantId=null;
        if(current.getType()==2){
            merchantId=current.getId();
        }
        //待付款笔数  consignment
        int  paymentOnBehalf  =this.ordersMapper.ordersStatistic("1",merchantId);

        //待发送发货   prepareGoodsBehalf
        int consignment=this.ordersMapper.ordersStatistic("2",merchantId);

        //已派送 collectGoodsBehalf
        int collectGoodsBehalf=this.ordersMapper.ordersStatistic("3",merchantId);

        //已完成 completed
        int completed=this.ordersMapper.ordersStatistic("4",merchantId);

        //已取消  cancel
        int cancel=this.ordersMapper.ordersStatistic("5",merchantId);

        OrdersStatisticResp resp=new OrdersStatisticResp();
        resp.setCancel(cancel);
        resp.setCompleted(completed);
        resp.setConsignment(consignment);
        resp.setCollectGoodsBehalf(collectGoodsBehalf);
        resp.setPaymentOnBehalf(paymentOnBehalf);
        resp.setTotalCount(cancel+completed+consignment+collectGoodsBehalf+paymentOnBehalf);

        return resp;
    }

    /**
     * 根据订单查询明细
     * @param orderId
     * @return
     */
    @Override
    public OrderViewResp findById(Long orderId) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getNumber,orderId);
        Orders dbOrder = this.ordersMapper.selectOne(queryWrapper);
        if(Objects.isNull(dbOrder)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        OrderViewResp resp = OrdersConvert.INSTANCE.convert(dbOrder);

        //查询明细
        LambdaQueryWrapper<OrderDetail> detailLambdaQueryWrapper=new LambdaQueryWrapper<>();
        //订单主键
        detailLambdaQueryWrapper.eq(OrderDetail::getOrderId,dbOrder.getId());
        detailLambdaQueryWrapper.select(OrderDetail::getId,OrderDetail::getName,OrderDetail::getImage,OrderDetail::getNumber,OrderDetail::getAmount,OrderDetail::getDishFlavor);
        List<OrderDetail> orderDetailList = this.orderDetailService.list(detailLambdaQueryWrapper);

        resp.setDrug(OrdersConvert.INSTANCE.convert(orderDetailList));

        return resp;
    }

    /**
     * 更改收货人地址
     * @param req
     * @return
     */
    @Override
    public boolean updateConsignee(UpdateConsigneeReq req) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getNumber, req.getId());

        Orders db = this.baseMapper.selectOne(queryWrapper);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }


        return false;
    }
}




